<?php
/**
 * IdentityService.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-05-11 16:11:38
 * @modified    2023-05-11 16:11:38
 *
 */

namespace App\Services;

use App\Models\UserModel;

class IdentityService
{
    private $userId;
    private $user;

    const SUPER_ROLE_NAMES = ['超级管理员', '系统管理员'];

    public function __construct($userId)
    {
        $this->userId = $userId;
        if (is_null($this->user)) {
            $this->setUser();
        }
    }

    /**
     * 是否是超级管理员: ID = 1 || 角色名 = 超级管理员 || 角色名 = 系统管理员
     *
     * @return bool
     */
    public function isSuperUser(): bool
    {
        $roles = $this->getRoleNames();
        if ($this->userId == 1 || array_intersect(self::SUPER_ROLE_NAMES, $roles)) {
            return true;
        }
        return false;
    }

    // 获取登录账号拥有的角色名称
    private function getRoleNames()
    {
        $roles = $this->user->roles;
        if (!$roles->count()) {
            return [];
        }
        $roleNames = [];
        foreach ($roles as $role) {
            $roleNames[] = $role->role->name ?? '';
        }
        return array_unique($roleNames);
    }

    private function setUser()
    {
        $user = UserModel::with(['roles.role'])->find($this->userId);
        $this->user = $user;
    }
}